package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.heima.file.service.impl.MinIOTemplate;
import com.heima.utils.baidu.Base64Util;
import com.heima.utils.baidu.HttpUtil;
import com.heima.wemedia.config.BaiduTokenCache;
import com.heima.wemedia.service.BaiduScanService;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @author xiaquanen
 * @version 1.0
 * @project heima-leadnews
 * @date 2024/7/23 10:30:47
 */
@Service
public class BaiduScanServiceImpl implements BaiduScanService {

    @Autowired
    private MinIOTemplate minIOTemplate;

    @Autowired
    private BaiduTokenCache baiduTokenCache;

    /**
     * 审核文章
     *
     * @param content
     * @return
     */
    @Override
    public Integer scanText(String content) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined";
        try {
            String param = "text=" + URLEncoder.encode(content, "utf-8");
            HashMap<String, String> tokenCache = baiduTokenCache.getTokenCache();
            String token =tokenCache.get("accessToken");
            //如果集合中没有token，就重新获取
            if(token==null)
            {
               token = getToken();
               tokenCache.put("accessToken",token);
            }
            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = token;

            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);
            return JSONObject.parseObject(result).getInteger("conclusionType");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 4;
    }

    /**
     * 审核图片
     *
     * @param imageUrl
     * @return
     */
    @Override
    public Integer scanImage(String imageUrl) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined";
        try {
            // 本地文件路径
            byte[] imgData = minIOTemplate.downLoadFile(imageUrl);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            HashMap<String, String> tokenCache = baiduTokenCache.getTokenCache();
            String token =tokenCache.get("accessToken");
            //如果集合中没有token，就重新获取
            if(token==null)
            {
                token = getToken();
                tokenCache.put("accessToken",token);
            }

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = token;

            String result = HttpUtil.post(url, accessToken, param);

            return JSONObject.parseObject(result).getInteger("conclusionType");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return 4;
    }

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static String getToken()
    {
        try{
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "");
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/oauth/2.0/token?client_id=Eh4oMwSiyYqPRBiqqOB7bH8M&client_secret=SgOJehZwykfaTq2i9EsqAoTXswclMy1H&grant_type=client_credentials")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            String string = response.body().string();
            return JSONObject.parseObject(string).getString("access_token");
        }catch (Exception e)
        {
            return null;
        }
    }
}


